/******************************************************
 *                                                     
 *              Score System               
 *                                                     
 *******************************************************/

/**
 * MultipartSupport.java
 *
 * 针对Multipart/form-data编码方式post的数据进行简单的封装
 * 主要是用户文件上传部分
 *
 * @author sundy
 * @version 0.0.1
 * lastModified 2011-01-01
 */

package com.sundy.tools;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.sundy.core.Common;
import com.sundy.core.Configuration;

public class MultipartSupport {
	private HashMap<String, String> parameters = new HashMap<String, String>();
	private HashMap<String, FileItem> fileitems = new HashMap<String, FileItem>();
	private List<String> filenames = new ArrayList<String>();

	@SuppressWarnings("unchecked")
	public MultipartSupport(HttpServletRequest request) throws IOException {
		String tempDir = Configuration.getProperty("/config/tmp-dir");
		long maxSize = Integer.valueOf(Configuration
				.getProperty("/config/upload-max"));

		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(new File(tempDir));

		ServletFileUpload upload = new ServletFileUpload(factory);

		try {
			upload.setSizeMax(maxSize);
			List<FileItem> items = upload.parseRequest(request);
			for (Iterator i = items.iterator(); i.hasNext();) {
				FileItem item = (FileItem) i.next();
				if (item.isFormField()) {
					parameters.put(item.getFieldName(), item
							.getString(Common.defaultEncode));
				} else {
					parameters.put(item.getFieldName(), item.getName());
					fileitems.put(item.getFieldName(), item);
				}
			}
		} catch (Exception e) {
			IOException t = new IOException(e.getMessage());
			t.initCause(e);
			throw t;
		}
	}

	public String getParameter(String name) {
		return parameters.get(name);
	}

	public List<String> getParameterNames() {
		Iterator<String> itr = parameters.keySet().iterator();
		List<String> list = new ArrayList<String>();
		while (itr.hasNext()) {
			list.add(itr.next());
		}
		return list;
	}

	public List<String> getFileNames() {
		return filenames;
	}

	public FileItem getFile(String name) {
		return fileitems.get(name);
	}
}
